/**
 * @developer：MR·Feng
 * 账单详情
 */

import styles from '@/styles/bill/billdetail.less';

import _ from 'lodash';
import { withRouter } from 'umi';
import React, { useEffect, useState } from 'react';
import {
    Table,
    Space,
    Form,
    Input,
    Button,
    Modal,
    Select,
    Popconfirm,
    message,
} from 'antd';
import Request from '@/api/baseRequest';
import { isnullObj, delKey } from '@/utils/datas';

const { Option } = Select;
const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
};

function Resource({ history, location }) {
    const { state } = location;
    const [parameter] = useState(_.cloneDeep(state));
    const [form] = Form.useForm();
    const [type, settype] = useState('');
    const [data, setdata] = useState([]);
    const [company, setcompany] = useState([]);
    const [update, setupdate] = useState(false);
    const [loading, setloading] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [pagination, setpagination] = useState({ current: 1, pageSize: 10 });

    // table显示格式
    const columns = [
        {
            title: '资源子公司名称',
            dataIndex: 'company_name',
            align: 'center',
            width: '40%',
        },
        {
            title: '比例',
            dataIndex: 'bili',
            align: 'center',
            width: '20%',
            render: (text) => `${text}%`,
        },
        {
            title: '费用',
            dataIndex: 'cost',
            align: 'center',
            width: '20%',
        },
        {
            title: '操作',
            dataIndex: 'id',
            key: 'id',
            align: 'center',
            width: '20%',
            render: (text, record) => (
                <Space size="middle" className={styles.operation}>
                    <span>
                        <span onClick={() => showModal(record, 'modify')}>
                            编辑
                        </span>
                        <Popconfirm
                            title="确定删除此资源子公司?"
                            onConfirm={() => showModal(record, 'delete')}
                            onCancel={cancel}
                            okText="确定"
                            cancelText="取消"
                        >
                            <span>删除</span>
                        </Popconfirm>
                    </span>
                </Space>
            ),
        },
    ];

    // 页数改变
    const handleTableChange = (pagination) => setpagination(pagination);

    // 蒙层确定操作
    const handleCreate = () => {
        form.validateFields()
            .then(() => {
                let params = _.cloneDeep(form.getFieldValue());
                handleCreateEditDelete(params);
                setIsModalVisible(false);
                form.resetFields();
            })
            .catch(() => {
                message.warning('请填写必填项');
            });
    };

    // 添加\编辑\删除列表\一键删除
    const handleCreateEditDelete = (params, type) => {
        if (['del'].includes(type))
            params = {
                action: 'deleteall',
            };
        Request.postResource(params, parameter.id).then((res) => {
            if ([200, '200', 'OK'].includes(res.status)) {
                message.success(res.message || '添加成功');
                setupdate(!update);
            } else {
                message.error(res.message || '信息错误');
            }
        });
    };

    // 显示蒙层
    const showModal = (val, type) => {
        settype(type);
        form.setFieldsValue({
            action: type,
        });
        if (['delete', 'modify'].includes(type)) {
            form.setFieldsValue({
                company_id: val.company_id,
                bili: val.bili,
            });
        }
        if (['delete', 'calculate'].includes(type)) {
            let params = _.cloneDeep(form.getFieldValue());
            if (['calculate'].includes(type))
                params = delKey(params, ['company_id', 'bili']);
            handleCreateEditDelete(params);
        }
        if (['add', 'modify'].includes(type)) {
            setIsModalVisible(true);
        }
    };

    // 蒙层返回操作
    const handleCancel = () => {
        setIsModalVisible(false);
        form.resetFields();
    };

    // 气泡取消操作
    const cancel = (e) => message.warn('取消删除');

    const cancelBill = () => {
        let {
            billform: { id, month },
            pagination,
        } = parameter;
        let data = { id, month, pagination };
        history.push({ pathname: '/bill', state: { ...data } });
    };

    // table footer
    const tableFooter = () => (
        <aside className={styles.tableFooter}>
            <Button onClick={cancelBill}>返回</Button>
        </aside>
    );

    // 副作用操作
    useEffect(async () => {
        setloading(true);
        if (isnullObj(company)) {
            const companyinfo = await Request.getCompany();
            setcompany(companyinfo.data);
        }
        Request.getResource({ id: parameter.id }).then((res) => {
            setdata(res);
            setloading(false);
        });

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [update]);

    return (
        <section className={styles.billdetail}>
            <Button
                type="primary"
                style={{ marginBottom: '15px' }}
                onClick={() => showModal(null, 'add')}
            >
                新增
            </Button>
            <Button
                style={{ margin: '0 0 15px 10px' }}
                onClick={() => showModal(null, 'calculate')}
            >
                计算
            </Button>
            <Button
                style={{ margin: '0 0 15px 10px' }}
                onClick={() => handleCreateEditDelete({}, 'del')}
            >
                一键删除
            </Button>
            <Modal
                title={
                    type === 'add'
                        ? '添加资源子公司'
                        : type === 'modify'
                        ? '编辑资源子公司'
                        : '资源子公司'
                }
                visible={isModalVisible}
                onOk={handleCreate}
                onCancel={handleCancel}
            >
                <Form {...layout} form={form} className={styles.billdetailForm}>
                    <Form.Item
                        label="资源子公司"
                        name="company_id"
                        rules={[
                            { required: true, message: 'Please input name!' },
                        ]}
                    >
                        <Select
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择资源子公司"
                        >
                            {(company || []).map((item) => (
                                <Option key={item.id} value={item.id}>
                                    {item.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="比例"
                        name="bili"
                        rules={[
                            { required: true, message: 'Please input user!' },
                        ]}
                    >
                        <Input suffix="%" />
                    </Form.Item>
                </Form>
            </Modal>
            <Table
                columns={columns}
                rowKey={(record) => record.id}
                dataSource={data.data}
                pagination={pagination}
                loading={loading}
                footer={tableFooter}
                onChange={handleTableChange}
            />
        </section>
    );
}

export default withRouter(Resource);
